import warnings
warnings.filterwarnings('ignore')
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(40)

from tensorflow.keras.models import Sequential
from tensorflow.keras import utils, optimizers, losses, metrics
from tensorflow.keras.layers import Dense, Activation, Conv2D, MaxPooling2D, Flatten

batch_size = 45
nb_output = 3
epochs = 50

# data sets
DATA_DIR = "../../../../large_data/DL1/_many_files/data3"
import os
import cv2
import numpy as np

def readData(path):
    x_images = []
    y_labels = []
    for image_name in os.listdir(path):
        image_path = os.path.join(path, image_name)
        image = cv2.imread(image_path)/255
        x_images.append(image)
        y_labels.append(image_name[0])
    return np.array(x_images), np.array(y_labels)

x_images, y_labels = readData(DATA_DIR)

x_images = x_images.astype('float32')

from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x_images, y_labels, train_size=0.7, random_state=123)

y_train = utils.to_categorical(y_train, nb_output)
y_test = utils.to_categorical(y_test, nb_output)

print(x_train.shape, y_train.shape)  # 60000x28x28x1
print(x_test.shape, y_test.shape)

model = Sequential([
    Conv2D(6, (5, 5), activation='relu'),
    MaxPooling2D((2, 2)),
    Conv2D(16, (3, 3), activation='relu'),
    MaxPooling2D((2, 2)),

    Flatten(),

    Dense(120, activation='relu'),
    Dense(84, activation='relu'),
    Dense(nb_output, activation='softmax')
])

model.compile(loss=losses.CategoricalCrossentropy(),
              optimizer=optimizers.Adam(0.001),
              metrics=['accuracy'])

model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs)

score = model.evaluate(x_test, y_test)
print('loss:', score[0])
print('acc:', score[1])
